import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

const service = axios.create({
  baseURL: 'http://big-event-vue-api-t.itheima.net',
  timeout: 10000

})
// 请求拦截器
service.interceptors.request.use((config) => {
  if (store.state.user.token) {
    config.headers.Authorization = store.state.user.token
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use((response) => {
  const { code, message } = response.data
  if (code === 0) {
    return response.data
  } else {
    Message({ type: 'error', message })
    return Promise.reject(new Error(message))
  }
}, async (error) => {
  if (error.response.status === 401) {
    // 提示  删除token  跳转
    Message({ type: 'error', message: '身份认证过期，请重新登录' })
    await store.dispatch('user/logout')
    router.push('/login')
    console.log(error)
  }

  return Promise.reject(error)
})

export default service
